
var randomScalingFactor = function(){ return Math.round(Math.random()*1000)};
window.onload = function(){
};

var json_ip_info;
// person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};





// $("#intro")  id="intro" 

// refer :  http://www.runoob.com/bootstrap/bootstrap-navigation-elements.html
function appendIPinfo_temp(obj)
{
    //var txt1="<p>Text.</p>";               // 以 HTML 创建新元素

    //var txt2=$("<p></p>").text("Text.");   // 以 jQuery 创建新元素
    //var txt3=document.createElement("p");  // 以 DOM 创建新元素
    //txt3.innerHTML="Text.";
    //$("#ip_info_container").append(txt1,txt2,txt3);         // 追加新元素

   //  
   // <ul class="nav nav-pills" id="ip_info_container" role="tablist">
   // </ul>

    var ss="test"
    var ip_info = `<li class="dropdown">
      <a class="dropdown-toggle" data-toggle="dropdown" href="#"> CH <span class="caret"></span></a>
      <ul class="dropdown-menu"  role="menu">
        <li><a href="#"  id="ip_info">`+ss+`</a></li>
        <li><a href="#"  id="ip_info">CSS</a></li>
        <li><a href="#" id="ip_info">JavaScript</a></li>
      </ul>
    </li>`;
    
       for (item in obj)
       {
           //console.log(item);
           ip_info = `<li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#"> `+item +`<span class="caret"></span></a>
                    <ul class="dropdown-menu"  role="menu">`;
           for (ip in obj[item])
           {
               //console.log("---"+obj[item][ip]);
               ip_info = ip_info + `<li><a href="#"  id="ip_info">`+obj[item][ip]+`</a></li>`
               
           }
          ip_info = ip_info+ `</ul>
                           </li>`;
          $("#ip_info_container").append(ip_info);  
       }

    $('a#ip_info').click(function () {
    // JS CODE
      console.log( this.text ); // or $(this).val()
      get_traffic_by_ip(this.text);

});

}
// later use :  https://github.com/5509/jQselectable
// http://bootsnipp.com/snippets/MRAVX
/*
        <li>
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu 3 <b class="caret"></b></a>
            <ul class="dropdown-menu">

                        <li class="dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>
                            <ul class="dropdown-menu">
                                    <li class="dropdown-submenu">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>
                                        <ul class="dropdown-menu">
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                        </ul>
                                    </li>
                            </ul>
                        </li>


                        <li class="dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>
                            <ul class="dropdown-menu">
                                    <li class="dropdown-submenu">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>
                                        <ul class="dropdown-menu">
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                        </ul>
                                    </li>

                                    <li class="dropdown-submenu">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown</a>
                                        <ul class="dropdown-menu">
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                            <li><a href="#">Another action</a></li>
                                        </ul>
                                    </li>
                            </ul>
                        </li>

            </ul>
        </li>
*/
function appendIPinfo(obj)
{
    var str="";
       for (id in obj)
       {
           str="";
           str=`<li>
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">`+id+`<b class="caret"></b></a>
            <ul class="dropdown-menu">`;
           console.log(id);
           for (isp in obj[id])
           {

               console.log("---"+isp);
               str=str + `<li class="dropdown-submenu">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown">`+isp+`</a>
                                <ul class="dropdown-menu">`;

               for (region in obj[id][isp])
               {
                  console.log("------"+region);
                  

                  str = str + `<li class="dropdown-submenu">
                                   <a href="#" class="dropdown-toggle" data-toggle="dropdown">`+region+`</a>
                                     <ul class="dropdown-menu">`;

                  for (ip in obj[id][isp][region])
                  {
                     console.log("---------"+obj[id][isp][region][ip]);
                     str=str+`<li><a href="#" id="ip_info">`+obj[id][isp][region][ip]+`</a></li>`;
                  }
                  /*
                  for(var i=0;i<100;i++)
                  {
                      str=str+`<li><a href="#" id="ip_info">`+obj[id][isp][region][ip]+`</a></li>`;
                  }
                  */
                 str=str + `</ul>
                    </li>`;
               }

              str=str + `</ul></li>`;
           }


           str=str + `</ul></li>`;

           $("#ip_info_container").append(str); 
       }

       $('a#ip_info').click(function () {
               // JS CODE
              console.log( this.text ); // or $(this).val()
              get_traffic_by_ip(this.text);

        });
}

$.get("/lumino/traffic.php?type=geo",function(data,status){
         //console.log(data);
         console.log("/lumino/traffic.php?type=geo"+ "and status is : " + status);
         var json = eval('(' + data + ')');
         console.log(json);
         var temp=new Array();
         var obj = new Object();
        for(var i=0,l=json.length;i<l;i++){
            if (!json[i]) 
            {
                continue;
            }
            console.log(json[i].data.country_id+" : "+ json[i].data.isp+" : " + json[i].data.region+" : "+json[i].data.ip);
            //temp.push([ json[i].data.country_id,json[i].data.ip]);


            if(json[i].data.isp=="")
            {
                json[i].data.isp="unkonwn";
            } 

            if(json[i].data.region=="")
            {
                json[i].data.region="unkonwn";
            } 

            if(!obj[json[i].data.country_id])
            {
               obj[json[i].data.country_id]= new  Object();
            }   

            if(!obj[json[i].data.country_id][json[i].data.isp])
            {

               obj[json[i].data.country_id][json[i].data.isp]= new  Object();
            }   

            if(!obj[json[i].data.country_id][json[i].data.isp][json[i].data.region])
            {

               obj[json[i].data.country_id][json[i].data.isp][json[i].data.region]= new  Array();
            } 


            obj[json[i].data.country_id][json[i].data.isp][json[i].data.region].push(json[i].data.ip)

       }
       console.log(obj);
       appendIPinfo(obj);

});

speed_chart_option = {
					    tooltip : {
					        trigger: 'axis',
					        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
					            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
					        }
					    },
					    legend: {
					        data:['upload','download']
					    },

					    grid: {
					        left: '3%',
					        right: '4%',
					        bottom: '3%',
					        containLabel: true
					    },
					    
					    xAxis : [
					        {
					            type : 'category',
					        }
					    ],
					    yAxis : [
					        {
					            type : 'value'
					        }
					    ],
					    series : [
					        {
					            name:'upload',
					            type:'bar',
					            stack: 'speed',
	
					        },
					        {
					            name:'download',
					            type:'bar',
					            stack: 'speed',
	
					        },

					    ]
					}


ip_speed_chart_option = {
        title: {
        text: '',
    },

    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data:['upload','download','total']
    },
    toolbox: {
        show: true,
        feature: {
            dataView: {readOnly: false},
            magicType: {type: ['line', 'bar']},
            restore: {},
            saveAsImage: {}
        }
    },
    xAxis:  {
        type: 'category',
        boundaryGap: false,
    },
    yAxis: {
        type: 'value',
    },
    series: [
        {
            name:'upload',
            type:'line',
          
        },
        {
            name:'download',
            type:'line', 
        },
        {
            name:'total',
            type:'line',

        }
    ]
};


//$("button").click(function(){
		$.get("/lumino/traffic.php",function(data,status){
		    // alert("数据: " + data + "\n状态: " + status);
                     //console.log(data);
                     var json = eval('(' + data + ')');
                     var ip_arrary = new Array();　
                     var upload_array = new Array();　
                     var download_array = new Array();　
                     var total_bindwidth=0;
                     var total_bindwidth_upload=0;
                     var total_bindwidth_download=0;
                     $('fog_ip').empty()
				for(var i=0,l=json.length;i<l;i++){
					for(var key in json[i]){
					//console.log(key+':'+json[i][key]);
                                            if(key == 'fog_ip')
                                            {

                                                  ip_arrary.push(json[i][key])   
                                                  //jQuery("#fog_ip").append("<option value='"+json[i][key]+"'>"+json[i][key]+"</option>");  
                                            }
                                            if(key == 'fog_upload')
                                            {
                                                  upload_array.push(json[i][key])  
                                                  total_bindwidth_upload= total_bindwidth_upload+parseInt(json[i][key], 10); //returns 10
                                            }
                                            if(key == 'fog_download')
                                            {
                                                  download_array.push(json[i][key])  
                                                  total_bindwidth_download= total_bindwidth_download+parseInt(json[i][key], 10); //returns 10
                                            }
					}
				}
                    //console.log(ip_arrary);
                    //console.log(upload_array);
                    //console.log(download_array);
 
                    total_bindwidth = total_bindwidth_upload+total_bindwidth_download;



            var speed_chart = echarts.init(document.getElementById('speed-chart'));
            speed_chart_option.series[0].data=upload_array;
            speed_chart_option.series[1].data=download_array;
            speed_chart_option.xAxis[0].data=ip_arrary;

            speed_chart.setOption(speed_chart_option);


            show_total_bindwidth(total_bindwidth,"main_total",2);
            show_total_bindwidth(total_bindwidth_upload,"main_total_upload",20);
            show_total_bindwidth(total_bindwidth_download,"main_total_download",20);

			get_traffic_by_ip($("#fog_ip").val()) ;


	 });
//});
function get_traffic_by_ip(ip)
{

	var queryurl = "/lumino/traffic.php?ip="+ip
            console.log( "url is : "+queryurl );
            $.get(queryurl,function(data,status){
                // console.log( data );

                var json = eval('(' + data + ')');
                     var time_arrary = new Array();　
                     var upload_array = new Array();　
                     var total_array = new Array();　
                     var download_array = new Array();
				for(var i=0,l=json.length;i<l;i++){
					for(var key in json[i]){
                               
                                            if(key == 'fog_upload')
                                            {
                                                  upload_array.push(json[i][key])   
                                            }
                                            if(key == 'fog_download')
                                            {
                                                  download_array.push(json[i][key])   
                                            }
                                            if(key == 'fog_last_time')
                                            {
                                                  var newDate = new Date();
                                                  newDate.setTime(json[i][key] * 1000);
                                                  //console.log(newDate.toLocaleString());
                                                  time_arrary.push(newDate.toLocaleString())  
                                            }
					}
                    total_array.push(parseInt(upload_array[i])+parseInt(download_array[i]));
				}


            //console.log(  upload_array.reverse());
            //console.log(  download_array.reverse());

            ip_speed_chart_option.title.text=ip;
           
            var ip_speed_chart = echarts.init(document.getElementById('ip-speed-chart'));
            ip_speed_chart_option.series[0].data=upload_array.reverse();
            ip_speed_chart_option.series[1].data=download_array.reverse();
            ip_speed_chart_option.series[2].data=total_array.reverse();
            ip_speed_chart_option.xAxis.data=time_arrary.reverse();
            ip_speed_chart.setOption(ip_speed_chart_option);
      });

}
$('#fog_ip').on('change', function() {
            console.log( this.value ); // or $(this).val()   
});



function show_total_bindwidth(total_bindwidth,ip,ratio)
{
   var myChart_total = echarts.init(document.getElementById(ip));

	 var  option = {
	    backgroundColor: '#1b1b1b',
	    tooltip : {
	        formatter: "{a} <br/>{c} {b}"
	    },
	    toolbox: {
	        show : true,
	        feature : {
	            mark : {show: true},
	            restore : {show: true},
	            saveAsImage : {show: true}
	        }
	    },
        series : [
        {
            name:'速度',
            type:'gauge',
            min:0,
            max:550,
            splitNumber:11,
            radius: '98%',
            axisLine: {            // 坐标轴线
                lineStyle: {       // 属性lineStyle控制线条样式
                    color: [[0.09, 'lime'],[0.82, '#1e90ff'],[1, '#ff4500']],
                    width: 3,
                    shadowColor : '#fff', //默认透明
                    shadowBlur: 10
                }
            },
            axisLabel: {            // 坐标轴小标记
                textStyle: {       // 属性lineStyle控制线条样式
                    fontWeight: 'bolder',
                    color: '#fff',
                    shadowColor : '#fff', //默认透明
                    shadowBlur: 10
                }
            },
            axisTick: {            // 坐标轴小标记
                length :15,        // 属性length控制线长
                lineStyle: {       // 属性lineStyle控制线条样式
                    color: 'auto',
                    shadowColor : '#fff', //默认透明
                    shadowBlur: 10
                }
            },
            splitLine: {           // 分隔线
                length :25,         // 属性length控制线长
                lineStyle: {       // 属性lineStyle（详见lineStyle）控制线条样式
                    width:3,
                    color: '#fff',
                    shadowColor : '#fff', //默认透明
                    shadowBlur: 10
                }
            },
            pointer: {           // 分隔线
                shadowColor : '#fff', //默认透明
                shadowBlur: 5
            },
            title : {
                textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    fontWeight: 'bolder',
                    fontSize: 20,
                    fontStyle: 'italic',
                    color: '#fff',
                    shadowColor : '#fff', //默认透明
                    shadowBlur: 10
                }
            },
            detail : {
                backgroundColor: 'rgba(30,144,255,0.8)',
                borderWidth: 1,
                borderColor: '#fff',
                shadowColor : '#fff', //默认透明
                shadowBlur: 5,
                offsetCenter: [0, '50%'],       // x, y，单位px
                textStyle: {       // 其余属性默认使用全局文本样式，详见TEXTSTYLE
                    fontWeight: 'bolder',
                    color: '#fff'
                }
            },
            data:[{value: 40, name: 'M bps/s'}]
        }
    ]
};


	         console.log("show_total_bandwidth set option and total :"+total_bindwidth);
                     //option.series[0].data[0].value = (Math.random() * 100).toFixed(2) - 0;
             option.series[0].data[0].value = total_bindwidth;

             //console.log(parseInt((total_bindwidth/11), 10));
             //console.log((total_bindwidth/11)+1);
             //console.log(((total_bindwidth/11)+1)*11);

             option.series[0].max = (parseInt((total_bindwidth/11), 10)+ratio)*11;
             
		     myChart_total.setOption(option);

}
  